<template>
  <div>

    <div class="container">
      <div class="handle-box">

        <el-input v-model="query.name" clearable placeholder="酒店名" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addVisible = true">新增</el-button>
        <!-- ✅ 导入导出按钮 -->
        <!-- <el-button
          type="success"
          icon="el-icon-upload2"
          class="mr10"
          @click="$refs.excelInput.click()"
        >导入 Excel</el-button> -->
        <input
          type="file"
          ref="excelInput"
          style="display: none"
          accept=".xlsx, .xls"
          @change="importFromExcel"
        />
        <el-button
          type="warning"
          icon="el-icon-download"
          @click="exportToExcel"
        >导出 Excel</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <!-- <el-table-column prop="hotelId" label="酒店标识"></el-table-column> -->
        <el-table-column prop="hotelName" label="酒店名称"></el-table-column>
        <el-table-column prop="hotelAddress" label="酒店地址"></el-table-column>
        <el-table-column prop="contactPhone" label="酒店电话"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row.hotelId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
        autocomplete="off"
      >
        <el-form-item label="酒店名称" prop="hotelName">
          <el-input v-model="form.hotelName" placeholder="请输入酒店名称" />
        </el-form-item>
      
        <el-form-item label="酒店地址" prop="hotelAddress">
          <el-input v-model="form.hotelAddress" placeholder="请输入酒店地址" />
        </el-form-item>
      
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="30%">
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="rules"
        label-width="90px"
        autocomplete="off"
      >
        <el-form-item label="酒店名称" prop="hotelName">
          <el-input v-model="addForm.hotelName" placeholder="请输入酒店名称" />
        </el-form-item>
      
        <el-form-item label="酒店地址" prop="hotelAddress">
          <el-input v-model="addForm.hotelAddress" placeholder="请输入酒店地址" />
        </el-form-item>
      
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="addForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
      
        <el-form-item label="酒店网址" prop="website">
          <el-input v-model="addForm.website" placeholder="请输入网址（可选）" />
        </el-form-item>
      
        <el-form-item label="备注" prop="notes">
          <el-input
            type="textarea"
            v-model="addForm.notes"
            placeholder="请输入备注信息（可选）"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import requests from '../utils/request'

export default {
    name: 'basetable',
    data() {
      // 手机正则，简单版：以1开头的11位数字
      const mobileReg = /^1[3-9]\d{9}$/;
      // 座机正则，含区号和分机号的情况
      const landlineReg = /^(\d{3,4}-)?\d{7,8}(-\d{1,4})?$/;
      return {
        query: {
            address: '',
            name: '',
            pageIndex: 1,
            pageSize: 30
        },
        tableData: [],
        multipleSelection: [],
        exportData: [],
        editVisible: false,
        addVisible: false,
        pageTotal: 0,
        form: {},
        addForm: {
          hotelName: '',
          hotelAddress: '',
          contactPhone: '',
          website: '',
          notes: ''
        },
        idx: -1,
        id: -1,
        rules: {
          hotelName: [
            { required: true, message: '酒店名称不能为空', trigger: 'blur' },
            { validator: (rule, value, callback) => {
                if (value && value.trim() !== '') callback();
                else callback(new Error('酒店名称不能为空'));
              }, trigger: 'blur' }
          ],
          hotelAddress: [
            { required: true, message: '酒店地址不能为空', trigger: 'blur' },
            { validator: (rule, value, callback) => {
                if (value && value.trim() !== '') callback();
                else callback(new Error('酒店地址不能为空'));
              }, trigger: 'blur' }
          ],
          contactPhone: [
            { required: true, message: '联系电话不能为空', trigger: 'blur' },
            { validator: (rule, value, callback) => {
                if (!value || value.trim() === '') {
                  callback(new Error('联系电话不能为空'));
                } else if (mobileReg.test(value.trim()) || landlineReg.test(value.trim())) {
                  callback();
                } else {
                  callback(new Error('联系电话格式不正确'));
                }
              }, trigger: 'blur' }
          ]
        }
      };
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/hotels/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          hotelName: this.query.name
        }).then(res=>{
          this.pageTotal = res.total
          this.tableData = res.data
        });
      },
      // 触发搜索按钮
      handleSearch() {
          this.loading();
      },
      // 删除操作
      handleDelete(row) {
        // 二次确认删除
        this.$confirm('确定要删除吗？删除后对应用户的住宿信息将会丢失哦', '提示', {
            type: 'warning'
        })
            .then(() => {
                requests.delete("/hotels/delById",{
                  hotelId: row
                }).then(res=>{
                  this.$message.success(res);
                  this.loading()
                })
            })
      },
      // 编辑操作
      handleEdit(row) {
        this.form = row;
        this.editVisible = true;
      },
      // 取消编辑
      cancelEdit() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.form.resetFields();
      },
      // 保存编辑
      saveEdit() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
        
          // 校验成功，调用接口
          requests.post("/hotels/edit", this.form)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.editVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
      // 单选、多选改变时调用
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的酒店');
          return;
        }
      
        this.$confirm(`确定删除这 ${this.multipleSelection.length} 项吗？删除后对应用户的住宿信息将会丢失哦`, '提示', {
          type: 'warning'
        })
          .then(() => {
            const ids = this.multipleSelection.map(item => item.hotelId);
            requests.post('/hotels/delByIds', ids)  // ✅ 注意这里直接传数组
              .then(res => {
                this.$message.success(res);
                this.loading(); // 重新加载表格
              })

          })
          
      },
      //新增操作
      handleAdd(row) {
        this.addForm = row;
        this.addVisible = true;
      },
      // 取消操作
      cancelAdd() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.addForm.resetFields();
      },
      // 保存操作
      saveAdd() {
        // 先校验表单
        this.$refs.addForm.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
        
          // 校验成功，调用接口
          requests.post("/hotels/add", this.addForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.addVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      //导出
      exportToExcel() {
        requests.get("/hotels/exportHotels").then(res => {
          // 转换导出数据格式
          let exportData = res.map(row => {
            return {
              // 酒店标识: String(row.hotelId || ''),
              酒店名称: row.hotelName || '',
              酒店地址: row.hotelAddress || '',
              酒店电话: row.contactPhone || ''
            };
          });
        
          // 保证表头存在，即使没有数据
          if (exportData.length === 0) {
            exportData.push({
              // 酒店标识: '',
              酒店名称: '',
              酒店地址: '',
              酒店电话: ''
            });
          }
        
          // 创建工作表
          const ws = XLSX.utils.json_to_sheet(exportData);
        
          // 设置列宽
          ws['!cols'] = [
            // { wch: 12 },  // 酒店标识
            { wch: 30 },  // 酒店名称
            { wch: 40 },  // 酒店地址
            { wch: 20 }   // 酒店电话
          ];
        
          // 设置“酒店标识”为文本
          const header = Object.keys(exportData[0]);
          const keys = Object.keys(ws);
          const idIndex = header.indexOf('酒店标识');
          if (idIndex >= 0) {
            const colLetter = String.fromCharCode(65 + idIndex);
            keys.forEach(key => {
              if (key.startsWith(colLetter) && key !== `${colLetter}1`) {
                const cell = ws[key];
                if (cell) {
                  cell.t = 's'; // 设置为字符串类型
                  cell.z = '@'; // 格式为文本
                }
              }
            });
          }
        
          // 导出 Excel 文件
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '酒店信息');
          XLSX.writeFile(wb, '酒店信息列表.xlsx');
        })
      },
      //导入
      importFromExcel(e) {
        const file = e.target.files[0];
        if (!file) return;
      
        const reader = new FileReader();
        reader.onload = (event) => {
          const data = new Uint8Array(event.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
        
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
        
          // 读取为 JSON 数组（跳过空行）
          let excelData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
          excelData = excelData.filter(row =>
            Object.values(row).some(v => v != null && String(v).trim() !== '')
          );
        
          if (!excelData || excelData.length === 0) {
            this.$message.warning('Excel 中无有效数据，无法导入');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 映射字段
          const mappedData = excelData.map((row, idx) => {
            const hotelId = Number(row['酒店标识']);
            if (isNaN(hotelId)) {
              console.warn(`第 ${idx + 2} 行“酒店标识”不是有效数字，跳过该行`, row);
              return null;
            }
          
            return {
              hotelId: hotelId,
              hotelName: row['酒店名称'] || '',
              hotelAddress: row['酒店地址'] || '',
              contactPhone: row['酒店电话'] || ''
            };
          }).filter(item => item !== null);
        
          if (mappedData.length === 0) {
            this.$message.warning('所有行数据无效，未生成可提交的数据');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 提交数据
          requests.post('/hotels/importHotels', mappedData)
            .then(response => {
              this.$message.success(response);
              this.loading(); // 重新加载页面数据
            })
          
          this.$refs.excelInput.value = '';
        };
      
        reader.readAsArrayBuffer(file);
      }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
